package cn.zn.framework.common.utils;

import cn.zn.framework.common.exception.RRException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

@Slf4j
public class QrCodeUtil {
    // 图片高度
    private static final int IMG_HEIGHT = 100;
    // 图片宽度
    private static final int IMG_WIDTH = 100;

    public void printQrCode(String content, OutputStream os) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定显示格式为GBK
        hints.put(EncodeHintType.CHARACTER_SET, "GBK");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, IMG_WIDTH, IMG_HEIGHT,
                    hints);
            // 生成png格式的图片保存到imgPath路径位置
            MatrixToImageWriter.writeToStream(bitMatrix, "png", os);
        } catch (Exception e) {
            log.error("", e);
            throw new RRException(e.getMessage());
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                log.error("", e);
                throw new RRException(e.getMessage());
            }
        }
    }
}
